package com.ybk.zs.interceptors;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2016/9/20.
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String reqToken = request.getParameter("token");//取参数中的token

        // token is not needed when debug
        //if (reqToken == null) return true;  // !! remember to comment this when deploy on server !!

        if (request.getRequestURI().indexOf("adminLogin") > 0) return true;//登录无需检查token

        HttpSession session = request.getSession();
        String sessionToken = (String) session.getAttribute("token");//取session中的token，所以token过期时间为session设置的过期时间

        if (reqToken!=null&&reqToken.length() > 0 && sessionToken != null && reqToken.equals(sessionToken)) {
            return true;//验证通过
        } else {
            response.sendRedirect("/html/login.html");//验证不通过，跳到登录页面
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
